package org.tokaf;

import java.util.ArrayList;

import javax.xml.xpath.XPathExpressionException;

/**
 * <p> QueryFinder finds queries in given XML file. XML should be partaged to
 * databases and then by methods. </p> <p> Copyright (c) 2006 </p> <p>
 * @author Alan Eckhardt
 * @version 1.0
 */
public class QueryFinder {
	public QueryFinder(String path, String platform) {
		this.path = path;
		this.platform = platform;
	}

	String path;

	String platform;

	public String replaceParams(String query, ArrayList params) {
		if (params == null)
			return query;
		String newQuery = query;
		for (int i = 0; i < params.size(); i++) {
			if (params.get(i) != null)
				newQuery = newQuery.replaceAll("#" + (i + 1) + "#", params.get(
						i).toString());
			else
				newQuery = newQuery.replaceAll("#" + (i + 1) + "#", "");
		}
		return newQuery;
	}

	public String getQuery(String methodName, int numberQuery, ArrayList params) {

		// 1. Instantiate an XPathFactory.
		javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory
				.newInstance();

		// 2. Use the XPathFactory to create a new XPath object
		javax.xml.xpath.XPath xpath = factory.newXPath();

		// 3. Compile an XPath string into an XPathExpression
		javax.xml.xpath.XPathExpression expression = null;
		try {
			expression = xpath.compile("/Databases/Database[@name = \""
					+ platform + "\"]/Method[@name=\"" + methodName
					+ "\"]/Query[@number=\"" + numberQuery + "\"]");
			String result = expression.evaluate(new org.xml.sax.InputSource(
					path));
			return replaceParams(result, params);
		} catch (XPathExpressionException e1) {
			e1.printStackTrace();
		}
		return null;

	}
}
